package utils

import (
	"fmt"
	"gdfs-center/logcat"
	"io/ioutil"
	"net"
	"net/http"
)

//获取本地IP
func GetLocalIPaddress() string {
	logcat.GetLog().Sugar().Info("获取本地ip")
	netInterfaces, err := net.Interfaces()
	if err != nil {
		logcat.GetLog().Sugar().Info("net.Interfaces failed, err:", err.Error())
		return ""
	}
	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			addrs, _ := netInterfaces[i].Addrs()

			for _, address := range addrs {
				if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						logcat.GetLog().Sugar().Info(ipnet.IP.String())
						return ipnet.IP.String()
					}
				}
			}
		}
	}
	return ""
}

//获取外网IP
func GetInternetIp() string {
	responseClient, errClient := http.Get("http://ip.dhcp.cn/?ip") // 获取外网 IP
	if errClient != nil {
		logcat.GetLog().Sugar().Info("获取外网 IP 失败，请检查网络\n")
		panic(errClient)
	}
	// 程序在使用完 response 后必须关闭 response 的主体。
	defer responseClient.Body.Close()

	body, _ := ioutil.ReadAll(responseClient.Body)
	clientIP := fmt.Sprintf("%s", string(body))
	logcat.GetLog().Sugar().Info(clientIP)
	return clientIP
}
